import Vue from 'vue'
import Router from 'vue-router'

const Login = () => import('components/login.vue')
const Home = () => import('view/Home.vue')
const Welcome = () => import('components/welcome.vue')
const Users = () => import('view/Users/users.vue')

// 1.安装Router
Vue.use(Router)

// 2.配置路由信息
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome,
      }, {
        path: '/users',
        component: Users,

      }

    ]
  }

]

// 3.创建路由对象
const router = new Router({
  mode: 'history',
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从哪里来
  // next 是一个函数，表示放行
  // 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage获取 保存的token
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token ，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})


// 4.导出
export default router
